<?php

class Crud_Form_Element_Column extends Crud_Form_Element
{
	/**
	 * Column for creating element.
	 * 
	 * @var Crud_Db_Table_Column
	 */
	protected $_column;
	
	/**
	 * Create element by table column.
	 * 
	 * @param Crud_Db_Table_Column $column
	 * @return void
	 */
	public function __construct($column)
	{
		if (!$column instanceof Crud_Section_Column) {
			throw new Crud_Exception('Cant create element by column. Unknow instance given');
		}
		$this->_column = $column;
		$name = $column->getKey();
		
		// Create class and store in object
		$class = $this->_getElementClass();
		$element = new $class($name);
		
		$this->setElement($element);
		
		$element->setRequired(!$column->isNull());
		$element->setLabel($column->getLabel());
		
		// Adding trim filtering
		$element->addFilter(new Zend_Filter_StringTrim());
		$element->addFilter(new Zend_Filter_Null(array(
			Zend_Filter_Null::STRING,
			Zend_Filter_Null::EMPTY_ARRAY,
		)));
		
/*		if ($column->isUnique()) {
			$table = $column->getTable()->getTableName();
			$name = $column->getName();
			$element->addValidator(new Zend_Validate_Db_NoRecordExists($table, $name));
		}*/
		
		$this->init();
	}
	
	public function init() {
		$maxLength = $this->getColumn()->getMaxLength();
		if ($maxLength) {
			$element = $this->getElement();

			$options = array(
				'min' => 0,
				'max' => $maxLength,
				'encoding' => 'UTF-8',
			);
			$element->addValidator(new Zend_Validate_StringLength($options));
			
			
			$element->setAttrib('maxlength', $maxLength);
				
			$size = $maxLength;
			if ($maxLength > 128) {
				$size = 128;
			}
				
			$element->setAttrib('size', $size);
		}
	}
	
	/**
	 * @return Crud_Section_Column
	 */
	public function getColumn()
	{
		return $this->_column;
	}
	
	/**
	 * Return element class name by column type.
	 * Try to get class from config or automatic from column type.
	 * 
	 * @return string
	 */
	protected function _getElementClass()
	{
		return 'Zend_Form_Element_Text';
	}
	
	/**
	 * Set value for given row.
	 * 
	 * @param Crud_Section_Row
	 * @param mixed $value
	 * @return void
	 */
	public function setRowValue(Crud_Section_Row $row, $value)
	{
		$method = $this->getColumn()->getSetter();
		$row->getRow()->$method($value);
	}
	
	/**
	 * Get default value by row.
	 * 
	 * @param Crud_Section_Row
	 * @return void
	 */
	public function getRowValue(Crud_Section_Row $row = null)
	{
		$column = $this->getColumn();
		if (!$row)  {
			$default = $column->getDefault();
			if ($default == 'CURRENT_TIMESTAMP') {
				$default = date('Y-m-d H:i');
			}
			
			return $default;
		}
		
		$data = $row->toArray();
		return $data[ $column->getKey() ];
	}
}